package com.rpay.service.auth.impl;

import com.rpay.common.dto.auth.AuthDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.exception.SmsException;
import com.rpay.common.exception.UserException;
import com.rpay.common.util.GoogleAuthenticator;
import com.rpay.dao.auth.AuthDao;
import com.rpay.model.auth.AuthDO;
import com.rpay.service.auth.IAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/5/5
 * @version 1.0
 */
@Service
public class AuthServiceImpl implements IAuthService {
    @Autowired
    private AuthDao authDao;

    @Override
    public AuthDTO createAuth(String email) {
        String secretKey = GoogleAuthenticator.generateSecretKey();
        String qrcodeUrl = GoogleAuthenticator.getQRBarcodeURL(email, secretKey);
        AuthDO authDO = new AuthDO();
        authDO.setEmail(email);
        authDO.setSecretKey(secretKey);
        authDao.insert(authDO);

        AuthDTO authDTO = new AuthDTO();
        authDTO.setSecretKey(secretKey);
        authDTO.setQrcodeUrl(qrcodeUrl);
        return authDTO;
    }

    @Override
    public boolean verifyAuth(String secretKey, Integer code) {
        long timeStamp = System.currentTimeMillis();
        GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator();
        boolean flag = googleAuthenticator.checkCode(secretKey, code, timeStamp);
        if (!flag) {
            throw new SmsException(PcsResultCode.SMS_GOOGLE_FAIL);
        }
        return true;
    }

    @Override
    public boolean updateValid(Integer id) {
        authDao.updateValid(id);
        return true;
    }

    @Override
    public AuthDTO getAuthDTO(String email, String secretKey) {
        AuthDO authDO = authDao.select(email, secretKey);
        if (authDO == null) {
            throw new UserException(PcsResultCode.USER_SECRET_NOT_EXISTED);
        }
        return convertDOToDTO(authDO);
    }

    private AuthDTO convertDOToDTO(AuthDO authDO) {
        AuthDTO authDTO = new AuthDTO();
        if (authDO != null) {
            authDTO.setId(authDO.getId());
            authDTO.setEmail(authDO.getEmail());
            authDTO.setSecretKey(authDO.getSecretKey());
        }
        return authDTO;
    }
}
